package com.powernode.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.RedisConstant;
import com.powernode.domain.Area;
import com.powernode.service.AreaService;
import com.powernode.mapper.AreaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 *
 */
@Service
@CacheConfig(cacheNames = "com.powernode.service.impl.AreaServiceImpl")
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area>
        implements AreaService {

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 由于地区这种数据太多
     * 所以使用redis进行数据缓存
     * 减轻sql和服务器的压力
     *
     * @param area
     * @return
     */
    @Override
    public List<Area> areaList(Area area) {
        List<Area> areas = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

        String areaStr = ops.get(RedisConstant.AREA_REDIS_KEY);
        if (StringUtils.hasText(areaStr)) {
            areas = JSON.parseArray(areaStr, Area.class);
        } else {
            areas = areaMapper.selectList(new LambdaQueryWrapper<Area>()
                    .eq(StringUtils.hasText(area.getAreaName()), Area::getAreaName, area.getAreaName()));
            //将list数组转为JSON格式的数组 进行保存
            String jsonArea = JSON.toJSONString(areas);
            ops.set(RedisConstant.AREA_REDIS_KEY, jsonArea);
        }

        return areas;
    }


    /**
     * 自提点的地址管理
     * @param pid
     * @return
     */
    @Override
    public List<Area> pickAddrAreaList(Long pid) {
        return areaMapper.selectList(new LambdaQueryWrapper<Area>()
        .eq(Area::getParentId,pid));
    }



    /**
     * 使用 springcache 也可以进行数据缓存
     * 1.导入cache依赖
     * 2.在启动类上开启 @EnableCaching
     * 3.在类上@CacheConfig(cacheNames = "本类的全限定名")
     * 4.在方法上  @Cacheable(key = "") 指定key值  返回值为value
     *
     * 但是保存格式容易超过 150kb
     * @param area
     * @return
     */
  /*  @Override
    @Cacheable(key = "'RedisConstant.AREA_REDIS_KEY'")
    public List<Area> areaList(Area area) {
        List<Area> areas = areaMapper.selectList(new LambdaQueryWrapper<Area>()
                .eq(StringUtils.hasText(area.getAreaName()), Area::getAreaName, area.getAreaName()));

        return areas;
    }*/
}




